<template>
  <div class="app-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>应用列表</span>
          <el-button type="primary" @click="handleAdd">新增应用</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
        <el-form-item label="应用名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入应用名称" clearable />
        </el-form-item>
        <el-form-item label="开发者" prop="developerName">
          <el-input v-model="queryParams.developerName" placeholder="请输入开发者名称" clearable />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" :value="0" />
            <el-option label="待审核" :value="1" />
            <el-option label="已发布" :value="2" />
            <el-option label="已下架" :value="3" />
            <el-option label="审核拒绝" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 应用列表 -->
      <el-table v-loading="loading" :data="appList" style="width: 100%">
        <el-table-column prop="name" label="应用名称" min-width="150">
          <template #default="{ row }">
            <div class="app-info">
              <el-image :src="row.icon" class="app-icon" fit="cover" />
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="developerName" label="开发者" min-width="120" />
        <el-table-column prop="version" label="版本" width="100" />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="downloads" label="下载量" width="100" sortable />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 0" type="info">草稿</el-tag>
            <el-tag v-else-if="row.status === 1" type="warning">待审核</el-tag>
            <el-tag v-else-if="row.status === 2" type="success">已发布</el-tag>
            <el-tag v-else-if="row.status === 3" type="danger">已下架</el-tag>
            <el-tag v-else-if="row.status === 4" type="danger">审核拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" sortable />
        <el-table-column prop="updateTime" label="更新时间" width="180" sortable />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" link @click="handleDetail(row)">详情</el-button>
            <el-button v-if="row.status === 2" type="danger" link @click="handleOffline(row)">下架</el-button>
            <el-button v-if="row.status === 3 || row.status === 4" type="success" link @click="handlePublish(row)">发布</el-button>
            <el-button v-if="row.status === 0" type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        class="pagination"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <!-- 应用详情对话框 -->
      <el-dialog
        v-model="detailDialogVisible"
        title="应用详情"
        width="800px"
        destroy-on-close
      >
        <div v-if="currentApp" class="app-detail">
          <div class="app-header">
            <el-image :src="currentApp.icon" class="app-detail-icon" fit="cover" />
            <div class="app-header-info">
              <h2>{{ currentApp.name }}</h2>
              <div class="app-meta">
                <span>开发者：{{ currentApp.developerName }}</span>
                <span>版本：{{ currentApp.version }}</span>
                <span>分类：{{ currentApp.categoryName }}</span>
                <span>下载量：{{ currentApp.downloads }}</span>
                <span>状态：
                  <el-tag v-if="currentApp.status === 0" type="info">草稿</el-tag>
                  <el-tag v-else-if="currentApp.status === 1" type="warning">待审核</el-tag>
                  <el-tag v-else-if="currentApp.status === 2" type="success">已发布</el-tag>
                  <el-tag v-else-if="currentApp.status === 3" type="danger">已下架</el-tag>
                  <el-tag v-else-if="currentApp.status === 4" type="danger">审核拒绝</el-tag>
                </span>
              </div>
            </div>
          </div>
          
          <el-divider />
          
          <div class="app-description">
            <h3>应用描述</h3>
            <p>{{ currentApp.description }}</p>
          </div>
          
          <div class="app-screenshots">
            <h3>应用截图</h3>
            <el-scrollbar>
              <div class="screenshot-list">
                <el-image
                  v-for="(screenshot, index) in currentApp.screenshots"
                  :key="index"
                  :src="screenshot"
                  class="screenshot"
                  fit="cover"
                  :preview-src-list="currentApp.screenshots"
                  :initial-index="index"
                />
              </div>
            </el-scrollbar>
          </div>
          
          <div class="app-package">
            <h3>安装包信息</h3>
            <div class="package-info">
              <p>包名：{{ currentApp.packageName }}</p>
              <p>大小：{{ formatFileSize(currentApp.packageSize) }}</p>
              <p>MD5：{{ currentApp.packageMd5 }}</p>
            </div>
          </div>
          
          <div v-if="currentApp.status === 4" class="audit-result">
            <h3>审核结果</h3>
            <div class="result-info">
              <p>审核人：{{ currentApp.auditorName }}</p>
              <p>审核时间：{{ currentApp.auditTime }}</p>
              <p>审核意见：{{ currentApp.auditComment || '无' }}</p>
            </div>
          </div>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();

// 查询参数
const queryParams = reactive({
  name: '',
  developerName: '',
  categoryId: undefined,
  status: undefined,
  pageNum: 1,
  pageSize: 10
});

// 表单引用
const queryFormRef = ref<FormInstance>();

// 数据列表
const loading = ref(false);
const appList = ref<any[]>([]);
const total = ref(0);
const categoryOptions = ref<any[]>([]);

// 应用详情对话框
const detailDialogVisible = ref(false);
const currentApp = ref<any>(null);

// 获取分类选项
const fetchCategoryOptions = () => {
  // 模拟数据，实际项目中应该从API获取
  categoryOptions.value = [
    { id: 1, name: '工具' },
    { id: 2, name: '办公' },
    { id: 3, name: '教育' },
    { id: 4, name: '娱乐' },
    { id: 5, name: '社交' }
  ];
};

// 获取应用列表
const fetchAppList = () => {
  loading.value = true;
  
  // 模拟数据，实际项目中应该从API获取
  setTimeout(() => {
    const mockData = [];
    for (let i = 1; i <= 20; i++) {
      const categoryId = i % 5 + 1;
      mockData.push({
        id: i,
        name: `测试应用${i}`,
        icon: 'https://via.placeholder.com/50',
        developerName: `开发者${i % 5 + 1}`,
        version: `1.${i % 10}.0`,
        categoryId: categoryId,
        categoryName: categoryOptions.value.find(item => item.id === categoryId)?.name || '',
        downloads: Math.floor(Math.random() * 10000),
        status: i % 5,
        createTime: new Date(Date.now() - i * 86400000 * 2).toLocaleString(),
        updateTime: new Date(Date.now() - i * 86400000).toLocaleString(),
        description: '这是一个测试应用的详细描述，包含了应用的主要功能和特点。',
        screenshots: [
          'https://via.placeholder.com/800x400',
          'https://via.placeholder.com/800x400',
          'https://via.placeholder.com/800x400'
        ],
        packageName: `com.example.app${i}`,
        packageSize: 1024 * 1024 * (10 + i % 20),
        packageMd5: '0123456789abcdef0123456789abcdef',
        auditorName: i % 5 === 4 ? '管理员' : '',
        auditTime: i % 5 === 4 ? new Date(Date.now() - i * 43200000).toLocaleString() : '',
        auditComment: i % 5 === 4 ? '应用存在安全风险，审核拒绝' : ''
      });
    }
    
    appList.value = mockData;
    total.value = 100;
    loading.value = false;
  }, 500);
};

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1;
  fetchAppList();
};

// 重置查询
const resetQuery = () => {
  if (!queryFormRef.value) return;
  queryFormRef.value.resetFields();
  handleQuery();
};

// 新增应用
const handleAdd = () => {
  router.push('/app/form');
};

// 编辑应用
const handleEdit = (row: any) => {
  router.push(`/app/form?id=${row.id}`);
};

// 查看详情
const handleDetail = (row: any) => {
  currentApp.value = row;
  detailDialogVisible.value = true;
};

// 下架应用
const handleOffline = (row: any) => {
  ElMessageBox.confirm('确认要下架该应用吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟API调用
    setTimeout(() => {
      ElMessage.success('下架成功');
      
      // 更新列表中的状态
      const index = appList.value.findIndex(item => item.id === row.id);
      if (index !== -1) {
        appList.value[index].status = 3;
        appList.value[index].updateTime = new Date().toLocaleString();
      }
    }, 500);
  }).catch(() => {});
};

// 发布应用
const handlePublish = (row: any) => {
  ElMessageBox.confirm('确认要发布该应用吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    // 模拟API调用
    setTimeout(() => {
      ElMessage.success('发布成功');
      
      // 更新列表中的状态
      const index = appList.value.findIndex(item => item.id === row.id);
      if (index !== -1) {
        appList.value[index].status = 2;
        appList.value[index].updateTime = new Date().toLocaleString();
      }
    }, 500);
  }).catch(() => {});
};

// 删除应用
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认要删除该应用吗？该操作不可逆！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟API调用
    setTimeout(() => {
      ElMessage.success('删除成功');
      
      // 从列表中移除
      const index = appList.value.findIndex(item => item.id === row.id);
      if (index !== -1) {
        appList.value.splice(index, 1);
      }
    }, 500);
  }).catch(() => {});
};

// 分页大小变更
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size;
  fetchAppList();
};

// 页码变更
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page;
  fetchAppList();
};

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB';
  } else if (size < 1024 * 1024 * 1024) {
    return (size / (1024 * 1024)).toFixed(2) + ' MB';
  } else {
    return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
  }
};

onMounted(() => {
  fetchCategoryOptions();
  fetchAppList();
});
</script>

<style scoped>
.app-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.app-info {
  display: flex;
  align-items: center;
}

.app-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.app-detail {
  padding: 0 20px;
}

.app-header {
  display: flex;
  align-items: center;
}

.app-detail-icon {
  width: 80px;
  height: 80px;
  border-radius: 16px;
  margin-right: 20px;
}

.app-header-info h2 {
  margin: 0 0 10px 0;
  font-size: 20px;
}

.app-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  color: #606266;
  font-size: 14px;
}

.app-description,
.app-screenshots,
.app-package,
.audit-result {
  margin-top: 20px;
}

.app-description h3,
.app-screenshots h3,
.app-package h3,
.audit-result h3 {
  font-size: 16px;
  margin-bottom: 10px;
}

.screenshot-list {
  display: flex;
  gap: 10px;
  padding-bottom: 10px;
}

.screenshot {
  width: 200px;
  height: 120px;
  border-radius: 8px;
  cursor: pointer;
}

.package-info,
.result-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 8px;
}

.package-info p,
.result-info p {
  margin: 5px 0;
}
</style> 